<?php

namespace App\Dao;


use App\Exception\MessageException;
use App\Model\ChatRoomMicrophone;
use Hyperf\Context\ApplicationContext;

class ChatRoomMicrophoneDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }

    /**
     * Note - 下麦
     * DateTime 2024/9/11 12:17
     * User Admin
     * @param $room_number
     * @param $userId
     */
    public function downMic($room_number, $userId)
    {
        if (ChatRoomMicrophone::query()->where('room_number', $room_number)->where('uid', $userId)->exists()) {
            ChatRoomMicrophone::query()->where('room_number', $room_number)
                ->where('uid', $userId)->update(['mi_up_down' => 0, 'u_voice_status' => 1, 'a_voice_status' => 1, 'uid' => null]);
        }

    }

    /**
     * Note - 上麦
     * DateTime 2024/9/11 12:17
     * User Admin
     * @param $room_number
     * @param $userId
     * @param $miSeq
     * @param $inviteUid
     * @param $inviteTime
     */
    public function upMic($room_number, $userId, $miSeq, $inviteUid, $inviteTime)
    {
        $micro = ChatRoomMicrophone::query()->where('mi_seq', $miSeq)->where('room_number', $room_number)->first();
        if (!$micro) {
            throw new MessageException('麦克风不存在');
        }
        $micro = modelToArray($micro);
        if ($micro['mi_up_down'] == 1) {
            throw new MessageException('麦位被占用');
        }
        if ($micro['mi_seq_lock'] == 1) {
            // 麦位被锁定
            throw new MessageException('麦位被锁定');
        }
        $oldMiSeq = ChatRoomMicrophone::query()->where('room_number', $room_number)->where('uid', $userId)->value('mi_seq');
        if ($oldMiSeq >= 0) {
            ChatRoomMicrophone::query()->where('room_number', $room_number)->where('mi_seq', $miSeq)->delete();
            // 上麦
            ChatRoomMicrophone::query()->where('uid', $userId)->where('mi_seq', $oldMiSeq)->where('room_number', $room_number)->update(['mi_seq' => $miSeq]);

            $miInfo['room_number'] = $room_number;
            $miInfo['mi_seq'] = $oldMiSeq;
            $miInfo['mi_seq_lock'] = 0;// 0-正常；1-锁定
            $miInfo['mi_up_down'] = 0;// 用户是否在麦位：0-否；1-是
            ChatRoomMicrophone::query()->insert($miInfo);
        } else {
            // 上麦
            ChatRoomMicrophone::query()->where('mi_seq', $miSeq)->where('room_number', $room_number)->update([
                'mi_up_down' => 1,
                'uid' => $userId,
                'invite_uid' => $inviteUid,
                'invite_time' => $inviteTime
            ]);
        }


    }
}